package com.uchedao.seller.ui.car.publish.condition;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.utils.L;
import com.uchedao.seller.R;
import com.uchedao.seller.manager.AppInfoManager;
import com.uchedao.seller.db.DbHelper;
import com.uchedao.seller.inf.IOnResultBack;
import com.uchedao.seller.module.Condition;
import com.uchedao.seller.module.Draft;
import com.uchedao.seller.config.GlobalInfo;
import com.uchedao.seller.module.PaintThickness;
import com.uchedao.seller.ui.car.adapter.PaintThicknessAdapter;
import com.uchedao.seller.ui.car.adapter.PaintThicknessAdapter.PaintThicknessListener;
import com.uchedao.seller.ui.car.blue_tooth.DeviceListActivity;
import com.uchedao.seller.ui.car.blue_tooth.PaintActivity2Bluetooth;
import com.uchedao.seller.util.CoverImageUtil;
import com.uchedao.seller.widget.loadstate.UCheDaoRelativeLayout;
import com.uchedao.seller.widget.stickylistheaders.StickyListHeadersListView;

import java.util.ArrayList;

/**
 * 漆膜厚度检测
 */
public class ConditionPaintThicknessView extends UCheDaoRelativeLayout implements IOnResultBack {

    public static final int FORM_PAINT = 401;// 漆膜厚度检测跳过去
    // BLUETOOTH
    public static final int REQUEST_CONNECT_DEVICE = 1;


    //    private Condition condition = GlobalInfo.draft.condition.clone();
    private Condition condition;
    //    private ResultIntArrayPics[] paint_surface;
    private PaintThicknessAdapter paintThicknessAdapter;
    private TextView paint_obd_conn_tv;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    private int clickNum = 0;

    public ConditionPaintThicknessView(Context context) {
        super(context);
    }

    public ConditionPaintThicknessView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ConditionPaintThicknessView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 2) {
                ((ImageView) findViewById(R.id.coverView)).setImageResource(R.mipmap.main);
            } else if (msg.what == 1) {
                ((ImageView) findViewById(R.id.coverView)).setImageBitmap((Bitmap) msg.obj);
            }
        }
    };

    @Override
    public boolean save() {

        ContentValues values = new ContentValues();
        values.put(DbHelper.KEY_DRAFT_CONDITION, toJson(condition));

        int status = condition.getStatus();
        values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, status);

        // 若VIN值为空
        if (TextUtils.isEmpty(condition.config_info.vin))
            condition.config_info.vin = GlobalInfo.draft.car_vin;

            // 如果VIN值有更改
        else if (!condition.config_info.vin.equals(GlobalInfo.draft.car_vin)) {
            values.put(DbHelper.KEY_DRAFT_CAR_VIN, condition.config_info.vin);
        }

        // int status = GlobalInfo.draft.status[Draft.TYPE_CONDITION];
        // // 若原先状态为未完成，且数据已变动，则状态改变为已完成
        // if (GlobalInfo.draft.status[Draft.TYPE_CONDITION] !=
        // Draft.STATUE_FINISH) {
        // values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, Draft.STATUE_FINISH);
        // status = Draft.STATUE_FINISH;
        // }

        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.tempOwner, values)) {
            GlobalInfo.draft.condition = condition.clone();
            GlobalInfo.draft.car_vin = condition.config_info.vin;
            GlobalInfo.draft.status[Draft.TYPE_CONDITION] = status;
            L.i(toJson(GlobalInfo.draft.condition));

            // 必填项全部填写返回true
            if(condition.isPaintThicknessFinish())
                return true;
            else
                return false;
        }

        return false;
    }

    @Override
    public boolean dataChanged() {

//        L.i(toJson(condition));
//        L.i(toJson(GlobalInfo.draft.condition));
        return !toJson(condition).equals(toJson(GlobalInfo.draft.condition));
//        return false;
    }

    @Override
    public void initView() {

        LayoutInflater.from(mContext).inflate(R.layout.view_detection, this);

//        TextView subjectName = (TextView)findViewById(R.id.subject_tv);
//        subjectName.setText(R.string.accident_paint);
        StickyListHeadersListView stickListHeadersListView = (StickyListHeadersListView) findViewById(R.id.detection_listView);

        LinearLayout paintHeader = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.accident_paint_header, null, false);
        stickListHeadersListView.addHeaderView(paintHeader);

        //测试赋值专用
        ImageView test = (ImageView) paintHeader.findViewById(R.id.coverView);
        test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickNum += 1;
                if (clickNum >= 8) {

                    condition.paint_thickness = getTestData(condition.car_type_int);
                    paintThicknessAdapter.setData(condition.paint_thickness);
                    // 创建主视图
                    drawCarImg();
                }
            }
        });

        // ImageView coverView = (ImageView)
        // paintHeader.findViewById(R.id.coverView);
        // coverView.setImageResource(R.drawable.main);
        // ImageView coverView = (ImageView)
        // paintThicknessLayout.findViewById(R.id.coverView);

        paint_obd_conn_tv = (TextView) paintHeader.findViewById(R.id.paint_obd_conn_tv);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            paint_obd_conn_tv.setText(mContext.getString(R.string.bluetooth_is_not_available));
        } else {
            if (mBluetoothAdapter.isEnabled() && !TextUtils.isEmpty(AppInfoManager.getBluetoothAddress())
                    && !"null".equals(AppInfoManager.getBluetoothAddress())) {
                if (TextUtils.isEmpty(AppInfoManager.getBluetoothName()) || "null".equals(AppInfoManager.getBluetoothName())) {
                    AppInfoManager.setBluetoothName(AppInfoManager.getBluetoothAddress());
                }
                paint_obd_conn_tv.setText(AppInfoManager.getBluetoothName());
            } else {
                paint_obd_conn_tv.setText(mContext.getString(R.string.paint_obd_not_conn));
            }
        }

        //  开启蓝牙链接
        paintHeader.findViewById(R.id.paint_connect_odb_bt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, DeviceListActivity.class);
                ((Activity) mContext).startActivityForResult(intent, REQUEST_CONNECT_DEVICE);
            }
        });

        final String[] carTypes = GlobalInfo.resources.getStringArray(R.array.paint_car_type);
        // 设置默认车型
        if (TextUtils.isEmpty(condition.car_type)) {
            condition.car_type = carTypes[0];
            condition.car_type_int = 0;
        }

        final Button paint_car_type_bt = (Button) paintHeader.findViewById(R.id.paint_car_type_bt);
        // 设置车辆类型
        paint_car_type_bt.setText(condition.car_type);
        paint_car_type_bt.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(mContext).setTitle(R.string.paint_car_type)
                        .setItems(R.array.paint_car_type, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                showResetDataDialog(paint_car_type_bt, which);
                            }
                        }).show();
            }
        });

        // 判断蓝牙链接状态，读取数据信息
        paintHeader.findViewById(R.id.paint_get_obd_data_bt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        paintThicknessAdapter = new PaintThicknessAdapter(mContext, new PaintThicknessListener() {
            @Override
            public void onClick(int position) {

                Intent intent = new Intent(mContext, PaintActivity2Bluetooth.class);
                ArrayList<PaintThickness> arraylist = new ArrayList<PaintThickness>();
                for (PaintThickness paint : condition.paint_thickness)
                    arraylist.add(paint);
                intent.putExtra("PaintThickness", arraylist);
                intent.putExtra("position", position);
                ((Activity) mContext).startActivityForResult(intent, FORM_PAINT);

            }
        });
        // 初始化adapter
        setPaintThickness(condition.car_type_int);

        stickListHeadersListView.setAdapter(paintThicknessAdapter);

    }

    /**
     * 测试伪造数据
     */
    private PaintThickness[] getTestData(int carType) {

        PaintThickness[] paint_thickness;
        int[] textsResId = {R.array.paint_car_entries, R.array.paint_suv_entries, R.array.paint_sports_entries};
        int[] lenResId = {R.array.paint_car_points_entries, R.array.paint_suv_points_entries,
                R.array.paint_sports_points_entries};

        String[] pointsStr = GlobalInfo.resources.getStringArray(lenResId[carType]);
//            // int[] points = new int[pointsStr.length];
//            // for (int i = 0; i < points.length; i++) {
//            // points[i] = Integer.valueOf(pointsStr[i]);
//            // }

        String[] texts = GlobalInfo.resources.getStringArray(textsResId[carType]);

        // if (reset || condition.paint_thickness == null)
        paint_thickness = new PaintThickness[texts.length];

        // PaintThickness[] items = condition.paint_thickness;

        for (int i = 0; i < texts.length; i++) {
            paint_thickness[i] = new PaintThickness();
            paint_thickness[i].name = texts[i];
            paint_thickness[i].points = Integer.valueOf(pointsStr[i]);

            if (i == 4 || i == 6 || i == 7) {
                paint_thickness[i].max = 4520;
            } else {
                paint_thickness[i].max = 755;
            }


            // if (condition.paint_thickness[i].result == null) {
            paint_thickness[i].result = new ArrayList<Integer>();
            for (int k = 0; k < paint_thickness[i].points; k++) {

                if (i == 4 || i == 6 || i == 7) {
                    paint_thickness[i].result.add(8000);
                } else {
                    paint_thickness[i].result.add(700);
                }
            }
            // }
        }
        return paint_thickness;
    }

    @Override
    public void initDataAfterView() {

    }

    @Override
    public void initDataBeforView() {
//        if (GlobalInfo.draft == null) {
//            GlobalInfo.draft = new Draft();
//        }
        condition = GlobalInfo.draft.condition.clone();

    }

    @Override
    public void initListener() {

    }

    /**
     * 提示修改车型改重置数据
     *
     * @param bt
     * @param carType
     */
    private void showResetDataDialog(final Button bt, final int carType) {

        new AlertDialog.Builder(mContext).setTitle(R.string.prompt).setMessage(R.string.change_car_type_message)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            String[] values = GlobalInfo.resources.getStringArray(R.array.paint_car_type);

                            bt.setText(values[carType]);
                            // 设置车型
                            condition.car_type_int = carType;
                            condition.car_type = values[carType];
                            resetPaintThickness(carType);
                        }
                    }
                }).setNegativeButton(R.string.cancel, null).create().show();

    }

    /**
     * 重置漆膜厚度检测项目
     *
     * @param carType
     */
    private void resetPaintThickness(int carType) {
        condition.paint_thickness = null;
        setPaintThickness(carType);
    }

    /**
     * 设置漆膜厚度检测项目
     *
     * @param carType 车型
     */
    private void setPaintThickness(int carType) {
        if (condition.paint_thickness == null) {
            int[] textsResId = {R.array.paint_car_entries, R.array.paint_suv_entries, R.array.paint_sports_entries};
            int[] lenResId = {R.array.paint_car_points_entries, R.array.paint_suv_points_entries,
                    R.array.paint_sports_points_entries};

            String[] pointsStr = GlobalInfo.resources.getStringArray(lenResId[carType]);
            // int[] points = new int[pointsStr.length];
            // for (int i = 0; i < points.length; i++) {
            // points[i] = Integer.valueOf(pointsStr[i]);
            // }

            String[] texts = GlobalInfo.resources.getStringArray(textsResId[carType]);

            // if (reset || condition.paint_thickness == null)
            condition.paint_thickness = new PaintThickness[texts.length];

            // PaintThickness[] items = condition.paint_thickness;

            for (int i = 0; i < texts.length; i++) {
                // if (condition.paint_thickness[i] == null)
                condition.paint_thickness[i] = new PaintThickness();
                condition.paint_thickness[i].name = texts[i];
                condition.paint_thickness[i].points = Integer.valueOf(pointsStr[i]);
                condition.paint_thickness[i].max = -1;
                // if (condition.paint_thickness[i].result == null) {
                condition.paint_thickness[i].result = new ArrayList<Integer>();

                for (int k = 0; k < condition.paint_thickness[i].points; k++)
                    condition.paint_thickness[i].result.add(-1);
                // }
            }
        }
        // if (paintThicknessAdapter == null) {
        // paintThicknessAdapter = new PaintThicknessAdapter(this,
        // condition.paint_thickness, paintThicknessListener);
        // } else {
        paintThicknessAdapter.setData(condition.paint_thickness);
        // }

        // 绘制车膜厚度效果图
        drawCarImg();
    }

    private void drawCarImg() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = CoverImageUtil.createPaintCoverView(condition.paint_thickness,
                        (ImageView) findViewById(R.id.coverView));
                Message msg = new Message();
                System.out.println("ws----bitmap  " + bitmap);
                if (bitmap != null) {
                    msg.what = 1;
                } else {
                    msg.what = 2;
                }
                msg.obj = bitmap;
                handler.sendMessage(msg);
            }
        }).start();

    }

    public void onActivityResultView(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case FORM_PAINT:// 漆膜厚度
                    ArrayList<PaintThickness> paintThickness = (ArrayList<PaintThickness>) data
                            .getSerializableExtra("PaintThickness");
                    // paintThicknessAdapter.setData(paintThickness);
                    condition.paint_thickness = paintThickness.toArray(new PaintThickness[0]);
                    paintThicknessAdapter.setData(condition.paint_thickness);
                    // 创建主视图
//                    CoverImageUtil.createPaintCoverView(condition.paint_thickness,
//                            (ImageView) findViewById(R.id.coverView));
                    drawCarImg();
                    L.i("paintThickness = " + toJson(paintThickness));
                    // for (int i = 0; i < paintThicknessAdapter.getCount(); i++)
                    // L.i(toJson(paintThicknessAdapter.getItem(i)));
                    break;
                case REQUEST_CONNECT_DEVICE:
                    try {
                        if (mBluetoothAdapter == null) {
                            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                        }
                        // Get the device MAC address
                        String address = data.getExtras()
                                .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                        // Get the BLuetoothDevice object
                        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                        AppInfoManager.setBluetoothName(device.getName());
                        AppInfoManager.setBluetoothAddress(device.getAddress());
                        if (TextUtils.isEmpty(AppInfoManager.getBluetoothName())) {
                            AppInfoManager.setBluetoothName(device.getAddress());
                        }
                        paint_obd_conn_tv.setText(AppInfoManager.getBluetoothName());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

}
